package formulation;

import java.util.ArrayList;
import java.util.List;

import es.deusto.ingenieria.is.csp.formulation.Constraint;
import es.deusto.ingenieria.is.csp.formulation.Variable;

public class SumConstraint extends Constraint<Integer> {
	private List<Variable<Integer>> rightVariables;
	private List<Variable<Integer>> leftVariables;

	public SumConstraint(String name, List<Variable<Integer>> left, List<Variable<Integer>> right) {
		super(name, left);
		rightVariables = right;
		leftVariables = left;

	}

	@Override
	public boolean isSatisfied(Variable<Integer> var, Integer value) {
		int sumRighVariables = 0;
		int sumLeftVariables = 0;

		int valorAnterior = var.getValue();
		var.setValue(value);

		for (Variable<Integer> variable : rightVariables) {
			if (variable.getValue().equals(null) && !variable.equals(var)) {
				var.setValue(valorAnterior);
				return true;
			}
			else if (variable.hasValue()) {
				if (variable.getName().length() != 1) {
					sumRighVariables += variable.getValue() * 10;
				}
				else {
					sumRighVariables += variable.getValue();
				}
			}

		}

		for (Variable<Integer> variable : leftVariables) {
			if (variable.getValue().equals(null) && !variable.equals(var)) {
				var.setValue(valorAnterior);
				return true;
			}
			sumLeftVariables += variable.getValue();
		}
		if (sumRighVariables != sumLeftVariables) {
			return false;
		}
		else {
			return true;
		}

	}

	public List<Variable<Integer>> getRightVariables() {
		return rightVariables;
	}

	public List<Variable<Integer>> getLeftVariables() {
		return leftVariables;
	}

	public void addVariablesToConstraint() {
		addVariables((ArrayList<Variable<Integer>>) leftVariables);
		addVariables((ArrayList<Variable<Integer>>) rightVariables);
	}

}
